package router

import (
	"reflect"

	"github.com/gogf/gf/util/gmeta"

	"github.com/gogf/gf/v2/net/ghttp"

	"github.com/fastknifes/usdt-pay/internal/http/common/middleware"
)

type Controllers []interface{}

func Handler(group *ghttp.RouterGroup) {
	// 注册公开路由
	group.Middleware(middleware.CommonMiddleware)
	bindRouter(group, publicRouters)

	// 注册登录路由, 需要登录才能访问
	group.Middleware(middleware.LoginMiddleware)
	bindRouter(group, loginRouters)

	// 注册授权路由，需要明确给用户授权才能访问
	group.Middleware(middleware.AuthorizeMiddleware)
	bindRouter(group, authorizeRoutes)
}

func bindRouter(group *ghttp.RouterGroup, routers []interface{}) {
	for _, router := range routers {
		group.Bind(router)
	}
}

var publicRouters []interface{}
var loginRouters []interface{}
var authorizeRoutes []interface{}

// RegisterRouter 注册路由
func RegisterRouter(object interface{}) {
	methodVal := reflect.TypeOf(object)
	if methodVal.Kind() == reflect.Func {
		if methodVal.NumIn() == 2 {
			// 获取控制器方法的第二参数对象的反射信息，对应api/v*/system/*.go 文件内的请求类结构体
			var objectReq = reflect.New(methodVal.In(1))
			v := gmeta.Get(objectReq.Interface(), "access")
			if v.String() == "login" {
				loginRouters = append(loginRouters, object)
			} else if v.String() == "authorize" {
				authorizeRoutes = append(authorizeRoutes, object)
			} else {
				publicRouters = append(publicRouters, object)
			}
		}
	} else {
		publicRouters = append(publicRouters, object)
	}
}
